package com.dobby.okhttp.demo.omqq;

import okhttp3.*;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by jonas on 2017/2/10.
 */
public class OmqqPublisher {

    private OkHttpClient okHttpClient = new OkHttpClient();

    private String cookie = null;

    private OmqqPublisher(String cookie) {
        this.cookie = cookie;
    }

    public static OmqqPublisher create(String cookie) throws Exception {
        if(cookie == null || cookie.length() == 0) {
            throw new Exception("cookie缺失");
        } else {
            return new OmqqPublisher(cookie);
        }
    }

    private Map<String, String> addHeaders() throws Exception {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("accept","application/json, text/javascript, */*; q=0.01");
        headers.put("accept-language","zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4");
        headers.put("content-type","application/x-www-form-urlencoded; charset=UTF-8");
        headers.put("origin","https://om.qq.com");
        headers.put("user-agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36");
        headers.put("x-requested-with","XMLHttpRequest");
        if(null != this.cookie) {
            headers.put("cookie", this.cookie);
        } else {
            throw new Exception("缺少cookie信息");
        }
        return headers;
    }


    public String saveDraft(String title, String content) throws Exception {
        String saveUrl = "https://om.qq.com/article/save?relogin=1";

//        params.add(new NameValuePair("title", title));
//        params.add(new NameValuePair("content", content));
//        params.add(new NameValuePair("category_id", "40"));  // 默认指定一个分类：鸡汤
//        params.add(new NameValuePair("cover_type", "-1"));
//        params.add(new NameValuePair("type", "0"));
//        params.add(new NameValuePair("apply_olympic_flag", "0"));
//        params.add(new NameValuePair("apply_push_flag", "0"));
//        params.add(new NameValuePair("apply_reward_flag", "1"));

        FormBody formBody = new FormBody.Builder()
                .add("title", title)
                .add("content", content)
                .add("category_id", "40")
                .add("type", "0")
                .add("cover_type", "-1").build();

        Request request = new Request.Builder()
                .headers(Headers.of(addHeaders()))
                .url(saveUrl)
                .post(formBody)
                .build();
        Response response = okHttpClient.newCall(request).execute();
        String responseStr = response.body().string();
        System.out.println(responseStr);
        return responseStr;
    }

}
